<template>
  <div>
    <el-card>
      <el-button type="primary" @click="addrole = dialogFormVisible = true"
        >添加角色</el-button
      >
      <!-- 添加角色 -->
      <el-dialog title="新增角色" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="角色名称" :label-width="formLabelWidth">
            <el-input
              v-model="form.roleName"
              autocomplete="off"
              placeholder="不能为空"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" :label-width="formLabelWidth">
            <el-input v-model="form.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改角色 -->
      <el-dialog title="修改角色" :visible.sync="editdialog">
        <el-form :model="role">
          <el-form-item label="角色名称" :label-width="formLabelWidth">
            <el-input
              v-model="role.roleName"
              autocomplete="off"
              placeholder="不能为空"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" :label-width="formLabelWidth">
            <el-input v-model="role.roleDesc" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editdialog = false">取 消</el-button>
          <el-button type="primary" @click="saveRole">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限 -->
      <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="50%"
        @close="setRightDialogclosed"
      >
        <!-- 树形控件 -->
        <el-tree
          :data="list"
          :props="treePropps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="defKeys"
          ref="treeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allRights">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级全限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightByid(scope.row.id, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightByid(scope.row.id, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightByid(scope.row.id, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="roleName"> </el-table-column>
        <el-table-column label="描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteClick(scope.row)"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="rights(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import {
  getRoles,
  addRoles,
  roleDelete,
  editRole,
  delRightes,
  getTree,
  getRightsTree,
} from "api/user";
import { MessageBox, Message } from "element-ui";
export default {
  data() {
    return {
      //控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      //存放树形的数据
      list: [],
      //默认选中的节点
      defKeys: [],
      //树形控件的属性绑定对象
      treePropps: {
        label: "authName",
        children: "children",
      },
      //当前即将分配权限的角色id
      roleId: "",
      tableData: [],
      dialogFormVisible: false,
      formLabelWidth: "120px",
      form: {
        roleName: "",
        roleDesc: "",
      },
      //修改
      role: {},
      editdialog: false,
    };
  },
  methods: {
    //点按钮的同时，将当前角色身上的所有三级权限的id获取出来，放到一个空数组里面，并且把这个
    //数组通过属性绑定给到defKeys

    //分配权限的对话框
    async rights(role) {
      this.roleId = role.id;
      //获取所有权限的数据
      const data = await getTree();
      //把获取到的权限数据保存到data中
      this.list = data;
      console.log(this.list);
      this.getLeafKeys(role, this.defKeys);
      this.setRightDialogVisible = true;
    },

    //通过递归的形式，获取角色下所有三级权限的id，并保存到defKeys数组中
    getLeafKeys(node, arr) {
      //如果当前node不包含children属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => this.getLeafKeys(item, arr));
    },
    //监听分配权限对话框的关闭事件
    setRightDialogclosed() {
      this.defKeys = [];
    },

    //点击角色分配权限
    async allRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      await getRightsTree(this.roleId, { rids: idStr });

      Message.success("分配权限成功!");
      this.getRolesList();
      this.setRightDialogVisible = false;
    },

    //根据id删除对应的权限
    removeRightByid(id, rid) {
      MessageBox.confirm("此操作将永久删除嘛", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await delRightes(id,rid);
          this.getRolesList();
          Message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          Message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改 回填
    edit(row) {
      this.role = row;
      this.editdialog = true;
    },
    async saveRole() {
      try {
        await editRole(this.role.id, this.role);
        Message.success("更新成功");
        this.getRolesList();
      } catch (error) {}
      this.editdialog = false;
    },

    //删除
    deleteClick({ id, roleName }) {
      MessageBox.confirm(`此操作将永久删除【${roleName}】嘛?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          Message({
            type: "success",
            message: "删除成功!",
          });
          await roleDelete(id);
          this.getRolesList();
        })
        .catch(() => {
          Message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //添加角色
    async addRole() {
      try {
        if (this.form.roleName == "" || this.form.roleDesc == "") {
          return Message.error("添加失败，不能为空");
        }
        await addRoles(this.form);
        Message.success("添加成功");
        this.getRolesList();
      } catch (error) {}
      this.form = {};
      this.dialogFormVisible = false;
    },
    //获取角色列表
    async getRolesList() {
      try {
        const data = await getRoles();
        this.tableData = data;
      } catch (error) {
        console.log(error);
      }
    },
  },
  created() {
    this.getRolesList();
  },
};
</script>

<style scoped >
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
